Background

Row

Title

Trust in Institutions

Column

Nigerian Trust Religious and Traditional Leaders more

Column

Northern States Trust the President more

Nigerians in Kano State trust Religious Leaders more

Issue Perceptions

Column

Nigerians say the Government is Handling Basic Health Service better and Job Creation worse

General Media Use

Row

Radio Remains the Main Source of News in Nigeria

Column

Ogun State has the highest radio use, followed by Kaduna and Gombe State

Internet use is highest in federal Captial Territory, the capital of Nigera, followed by Borno State

---
title: "Emmanuel Maduneme"
output: 
  flexdashboard::flex_dashboard:
    theme: 
      version: 4
      bootswatch: litera
    orientation: columns
    vertical_layout: fill
    source_code: embed
---

```{r setup, warning=FALSE, include=FALSE}
library(pacman)
p_load(tidyverse, esquisse, dlookr, rio, here, readr, tidytext, knitr, janitor,
       expss, hrbrthemes, flextable, labelled, sjlabelled, colorblindr, forcats,
       treemap, flexdashboard, plotly, ragg, extrafonts, ggiraph, tmap,
     htmlwidgets, packcircles)


```

```{r, include=FALSE}
## Importing Data
afrobarometer_ngr <- import(here("afrobarometer_release-data_nig_r8_en_2021-03-31.sav"),
       setclass = "tbl_df") 

NGA1  <- sf::st_read(here("untitled", "gadm41_NGA_1.shp"))
selected_afrob <-  afrobarometer_ngr %>% 
  select(RESPNO, REGION, Q101:Q103, Q13:Q15C, Q16A, starts_with("Q41"), Q50A:Q50P_NIG, Q55A:Q56)
selected_afrob <-  selected_afrob %>% 
  mutate(states = REGION)
```



# Background {data-orientation=rows data-icon="fa-info-circle"}


 
 About Data {.sidebar}
--------------------------------------------------
**Background**

The `afrobarometer_ngr` data is a publicly available data set from [**Afrobarometer**](https://www.afrobarometer.org/data/), an non-profit African survey organization based in Ghana. According to their website, they "conducts public attitude surveys on democracy, governance, the economy, and society." The data set is part of their many data sets from African countries. Specifically, the `afrobarometer_ngr` data set is a 2022 8th round comprehensive survey on several topics from perceptions of democracy, elections and the media to attitudes towards different institutions in Nigeria.

Row {data-width=400} 
-----------------------------------------------------------------------
### Title {.no-title}

```{r,  fig.width= 6.5, fig.height= 7, fig.align='center'}
knitr::include_graphics(here( "final draft graphics", "perception_image.png"))
```




# Trust in Institutions {data-icon="ion-android-checkmark-circle"}

```{r, trust, warning=FALSE, include=FALSE}
## Recode Variables Trust

#   Missing    Not at all Just a little      Somewhat        A lot      Don’t know 
#       NA             0             1             2             3         4

temp <- selected_afrob[,12:25]
temp[temp== -1] <- NA
temp[temp==8] <- NA
temp[temp== 9] <- 4
temp[temp==0 ] <- 0
temp[temp==1] <- 1
temp[temp==2] <- 2
temp[temp==3] <- 3

temp <- set_labels(temp, labels = c( "Don’t know" = 4, "Not at all" = 0,"Just a little" = 1, "Somewhat" = 2, "A lot" = 3))
selected_afrob[,12:25] <- temp


## look_for(selected_afrob)  This dislays all the labels 


## Create Subset of dataset on Trust
temp2 <- selected_afrob %>%    
  select(starts_with("Q41"))
  
## Renaming Variables Trust
temp2 <- temp2 %>%
  rename( "President" = "Q41A",  "National Assembly" = "Q41B","INEC" = "Q41C", 
          "Local Govt Council" = "Q41D", "The Ruling Party (APC)" = "Q41E",
          "Opposition Parties" ="Q41F", "Police" = "Q41G",
          "Military/Army" = "Q41H", "Judiciary" = "Q41I",
          "Tax/revenue officials" = "Q41J", "Traditional leaders" = "Q41K",
          "Religious leaders" = "Q41L","State Governor" = "Q41M_NIG",
          "State Legislature" = "Q41N_NIG") 
  
  selected_afrob[,12:25] <- temp2
  
  
  #   Missing    Not at all Just a little      Somewhat        A lot      Don’t know 
#       NA             0             1             2             3         4
  
  ## Clean data for plotting
 Trust_Manipulation <- temp2 %>% 
 pivot_longer(
   cols = c(1:14),
    names_to = "institutions",
    values_to = "trust_scores") %>% 
   #Not at all/ Just a little = 1, Somewhat  = 2, A lot/Don't know = 3
   mutate(trust_scores_recd = case_when(trust_scores < 1 ~ 1,
                                        trust_scores == 2 ~ 2,
                                        trust_scores > 2 ~ 3)) %>% 
    group_by(institutions, trust_scores) %>% 
   na.omit()
 
 glimpse(Trust_Manipulation)
 
## Stacked Bar chart for trust in different institutions
  trust_plot <- Trust_Manipulation %>% 
   ggplot(aes(reorder(institutions, trust_scores_recd)))+
  geom_bar(aes(fill = as.factor(trust_scores_recd)),  position="fill") +
   coord_flip() +
    scale_fill_manual(values = c('#8da0cb','#fc8d62','#66c2a5'),
                      labels=c("Not at all/ A little", "Somewhat", "Alot")) +
    scale_y_continuous(labels = scales::percent) +
    theme_void() +
     theme(axis.line = element_blank(),
           panel.background = element_blank(),
           axis.ticks = element_blank(),
           axis.text.y = element_text(size = 10, family="Times", face="bold", hjust = 1, color = "grey10"),
           axis.text.x = element_text(size = 10, color = "grey10"),
        panel.grid.major.x = element_blank(),
        legend.title=element_blank()) +
     labs(x = "",
        y = "Frequency",
        caption = "Question: How much do you trust each of the following:")
    
  ## Just trying out plot_ly here 
percent <- function(x, digits = 2, format = "f", ...) {      # Create user-defined function
  paste0(formatC(x * 100, format = format, digits = digits, ...), "%")
}
 
    

```

## Trust {.sidebar}

**Overall Trust** 

The plots in this page explored the level of trust Nigerians had in different institutions. Overall, Religious and Traditional leaders are the most trusted group of people. The National Assembly, which is the main legislative body in the country as well as the Police were the least trusted groups in Nigeria.

**Trust in President/ Religious Leaders by State** 

Religious leaders are the most trusted groups in Nigeria. The map showing states that trust the president the most and the least. As is evident, States in the North (Islamic Majority) are more trusting of the President and Religious Leaders compared to the states in the South (Christian Majority).

## Column {data-width="300"}


### Nigerian Trust Religious and Traditional Leaders more

```{r, warning=FALSE}
trust_plot

```

```{r, echo=FALSE, eval=FALSE, include=FALSE}


Trust_Manipulation %>% 
    plot_ly(.,
  x = ~trust_scores_recd,
  y = ~ institutions,
  orientation = 'v',
  type = "bar",
  color = ~as.factor(trust_scores_recd),
  labels = ~percent(trust_scores_recd/sum(trust_scores_recd))) %>% 
layout(yaxis = list(categoryorder = "total ascending"),
      barmode = 'stack',
       xaxis = list(title = ""),
        yaxis = list(title ="Average Score"))

```


## Column {data-width="300"}

```{r, echo=FALSE, message=FALSE, warning=FALSE}
## trust by States

Trust_by_states <- selected_afrob %>% 
 ## characterize() %>% 
  mutate(states = REGION) %>% 
  select(48, 12:25) %>% 
  to_character(states) %>% 
  rename( "President" = "Q41A",  "National Assembly" = "Q41B","INEC" = "Q41C", 
          "Elected lG Council" = "Q41D", "The Ruling Party (APC)" = "Q41E",
          "Opposition Parties" ="Q41F", "Police" = "Q41G",
          "Military/Army" = "Q41H", "Judiciary" = "Q41I",
          "Tax/revenue officials" = "Q41J", "Traditional leaders" = "Q41K",
          "Religious leaders" = "Q41L","State Governor" = "Q41M_NIG",
          "State Legislature" = "Q41N_NIG")

Trust_by_states$states <-  str_to_sentence(Trust_by_states$states)


Trust_by_states <- Trust_by_states %>% 
  mutate(NAME_1 = case_when(states == "Fct abuja" ~ "Federal Capital Territory",
                           states == "Abia" ~ "Abia",
                           states == "Cross river" ~ "Cross River",
                           TRUE ~ (states)))


Trust_President <-  Trust_by_states %>% 
  group_by(NAME_1) %>% 
 tally(President) %>% 
  arrange(desc(n))

Trust_Religious_Leaders <-  Trust_by_states %>% 
  group_by(NAME_1) %>% 
 tally(`Religious leaders`) %>% 
  arrange(desc(n))
 
Trust_President$n <- as.numeric(Trust_President$n)
Trust_Religious_Leaders$n <-  as.numeric(Trust_Religious_Leaders$n)



Trust_President <- left_join(NGA1, Trust_President)
Trust_Religious_Leaders <- left_join(NGA1, Trust_Religious_Leaders)

Trust_President_plot <- Trust_President %>%  
  mutate(prop_score = n/sum(n, na.rm = T)) %>% 
ggplot() +
  geom_sf(aes(fill = prop_score))+
  scale_fill_gradient(name= "% of Trust Scores",
    low = "#e0f3db",
  high = "#43a2ca",
  space = "Lab",
  na.value = "white",
  guide = "colourbar",
  aesthetics = "fill",
   breaks = c(0.03, 0.06,0.09),
  labels = c("Low Trust","Mid Trust", "High Trust")) +
  theme_void() +
    labs(title = "Trust in the President by State",
        subtitle = "Share of Nigerians who say they they trust A lot",
        x = "",
        y = "",
        caption = "Data from Afrobarometer 2022 Round 8 Nigeria")
 


 ## Ggplot but did not use this.  
Trust_Religious_Leaders_plot <-  Trust_Religious_Leaders %>% 
  mutate(prop_score = n/sum(n, na.rm = T)) %>% 
ggplot() +
  geom_sf(aes(fill = prop_score))+
 scale_fill_gradient(name= "% of Trust Scores",
                     low = "#fff7bc",
                     high = "#d95f0e",
                     space = "Lab",
                     na.value = "white",
                     guide = "colourbar",
                     aesthetics = "fill",
   breaks = c(0.03, 0.06,0.09),
  labels = c("Low Trust","Mid Trust",  "High Trust")) +
  theme_void() +
   labs(title = "Trust in the Religious Leaders",
        subtitle = "Share of Nigerians who say they they trust A lot",
        x = "",
        y = "",
        caption = "Data from Afrobarometer 2022 Round 8 Nigeria")

```

### Northern States Trust the President more

```{r warning=FALSE}

tmap_mode("view")
 Trust_President %>%  
  mutate(proportion = n/sum(n, na.rm = T)) %>%  
  tm_shape() +
   tm_text("NAME_1", size = 0.5) +
  tm_polygons("proportion",
              palette = "Purples",
              border.col = "#333333", 
              style= 'cont',
              showNA = NA,
              colorNA = "grey90",
              interactive = TRUE,
              lwd = 0.3,
              title=c("Proportions"))+
    #tm_text("NAME_1", size = 0.5) +
  tm_layout(legend.outside = TRUE) 
   


```

### Nigerians in Kano State trust Religious Leaders more

```{r warning=FALSE}
## Trust_Religious_Leaders_plot


tmap_mode("view")
Trust_Religious_Leaders %>% 
    mutate(prop_score = (n/sum(n, na.rm = T))) %>%  
  tm_shape() +
  tm_polygons("prop_score",
              style= 'cont',
              border.col = "#666666",
              colorNA = "white",
              lwd = 0.3,
               lwd = 0.3,
              title=c("Proportions")) +
    tm_text("NAME_1", size = 0.5) +
  tm_layout(legend.outside = TRUE)
```

# Issue Perceptions {data-icon="ion-ios-briefcase-outline"}

## Issue Perceptions {.sidebar}
--------------------------------------

**Perception of Varied Issues in Nigeria** 

The plot explored Nigerian's evaluation of different pressing national issues. Nigerians rated the Federal Government relatively high in providing basic Health services and their handling of education. The lowest assessments were on electricity and job creation. Overall, on a scale of "1 to 5", the ratings were quite low.


```{r,  include=FALSE}
## First I created a subset of data that included all the issues interest.
percep <- selected_afrob %>% 
  select(starts_with("Q50"))


## I then recoded the variables so they can be calculated. 
percep[percep== -1] <- NA
percep[percep==8] <- NA
percep[percep== 9] <- 5
percep[percep==0 ] <- 0
percep[percep==1] <- 1
percep[percep==2] <- 2
percep[percep==3] <- 3
percep[percep==4] <- 4


## These are the new values:

## Missing   Very badly Fairly badly  Fairly well    Very well  Don't know
#  NA           1         2             3                   4     5

percep <- set_labels(percep, labels = c("Missing" = NA, 
                                        "Very badly" = 1, 
                                        "Fairly badly" = 2,
                                        "Fairly well" = 3,
                                        "Very well" = 4,
                                   "Don't know" = 5))

## I then joined it to the original dataset
selected_afrob[,26:41] <- percep



## Here I renamed the subset created so they are identifiable

percep2 <- percep %>%
  rename("Economy" = "Q50A",
          "Living Conditions" = "Q50B", "Job Creation" = "Q50C",
          "Keeping Prices" = "Q50D",
          "Narrowing Income Gap" ="Q50E",
          "Crime Reduction"  = "Q50F",
          "Basic Health Services" = "Q50G",
          "Education" = "Q50H",
          "Water and Santiation" = "Q50I",
          "Fighting Corruption" = "Q50J",
          "Infrastructure" = "Q50K",
          "Electricity" = "Q50L",
          "Resolving Violent Crime" = "Q50M",
          "Needs of Youths" = "Q50N",
          "RIghts & Opportunities for Disabled People" = "Q50O",
          "Addressing Armed Extremism" = "Q50P_NIG")
  
  
## I pivot longer in order to have the columns as values
percep3 <- percep2 %>% 
    select(1:3, 6, 7, 8, 10, 12, 16) %>%
    pivot_longer(
   cols = c(1:9),
    names_to = "Issues",
    values_to = "ratings") 

## This was a bit redundant but.... yeah. 
j <- percep3 %>% 
    group_by(Issues) %>% 
    summarize(avg_score = round(mean(ratings), digits = 2)) %>% 
    arrange(desc(avg_score))

## Here I began plotting the first bar chart
cbl <- c("#D53130", "#00929C", "#FFB6C2", "#184C52", "#3086E5",
         "#846B54", "#6D6F80", "#E4CA15", "#523316")


### Plotly Graph
issue_ratings_plotly <- j %>% 
   rename("Average_Score" = "avg_score") %>% 
  plot_ly(.,
  x = ~Issues, 
  y = ~Average_Score,
  type = "bar",
  marker = list(color = cbl)) %>% 
layout(xaxis = list(categoryorder = "total descending",
                    title = ""),
       yaxis = list(range=c(1,5), 
                     title ="Average Score"))
       



```

## Column {data-width="400"}

### **Nigerians say the Government is Handling Basic Health Service better and Job Creation worse**

```{r}
issue_ratings_plotly
```


# General Media Use {data-icon="ion-android-desktop"}

## Trust {.sidebar}

**General Media Use**

Nigerians still rely more on radio and Television as their main sources of news. In Nigeria, it is often a common phrase in the past that **radio is king**. That phrase still holds true in 2022, followed by Television and Newspapers. 



```{r,warning=FALSE, include=FALSE}
## As previously noted, a subset of media use columns, but but first, I changed the name
selected_afrob <-  selected_afrob %>% 
  mutate(states = REGION)

## Then... the subset...    
media_use <- selected_afrob %>% 
    select(Q55A:Q55E)
  

## Recoding values
media_use[media_use== -1] <- NA
media_use[media_use==8] <- NA
media_use[media_use== 9] <- 5
media_use[media_use==0 ] <- 0
media_use[media_use==1] <- 1
media_use[media_use==2] <- 2
media_use[media_use==3] <- 3   
media_use[media_use==4] <- 4


## Changed labels
media_use <- set_labels(media_use, labels = c("Missing" = NA, 
                                              "Never" = 0,
                                        "Less than once a month" = 1, 
                                        "A few times a month" = 2,
                                        "A few times a week" = 3,
                                        "Every day" = 4,
                                   "Don't know" = 5))

## Used this code to check the labels
### val_lab(media_use$Q55A)


## Renamed the columns
media_use <- media_use %>%
  rename("Radio" = "Q55A",
         "Television" = "Q55B",
         "Newspaper" = "Q55C",
         "Internet" = "Q55D",
         "Social Media" = "Q55E")

## Joined back to the original
selected_afrob[,42:46] <- media_use

### Some data wrangling in preparation for the plot. 
media_use_main <- selected_afrob %>% 
  select(1, 2, 48, 42:46) %>%
  rename("ID" = "RESPNO",
         "REGION" = "REGION",
         "states" = "states",
         "Radio" = "Q55A",
         "Television" = "Q55B",
         "Newspaper" = "Q55C",
         "Internet" = "Q55D",
         "Social Media" = "Q55E") %>% 
  to_character(REGION, states)

## Changed the state names to a sentence case
 media_use_main$states <-  str_to_sentence(media_use_main$states)


   ### Some more data wrangling so I can plot the data in Tableau. 
  media_use_main <- media_use_main %>% 
   mutate(states = case_when(states == "Fct abuja" ~ "Federal Capital Territory",
                             states == "Abia" ~ "Abia",
                             states == "Cross river" ~ "Cross River",
                             TRUE ~ (states)),
          state = states)
  
  
p_load(naijR)
# Create a data frame and view top rows
ss <- states()
numStates <- length(ss)
vv <- sample(LETTERS[1:5], numStates, TRUE)
Nigerian_states <- tibble(states = ss, letter = vv)
dd <- data.frame(state = ss, letter = vv)
#(search for useful packages scripts to find full_set)
full_set <- merge(x = dd, y = media_use_main, by = "state")
## Some more wrangling in preparation for plotting as well as for Tableau
full_set2 <-  full_set %>% 
 select(1, 6:10) %>% 
  pivot_longer(
    cols = c(2:6),
    names_to = "media_type",
    values_to = "rating"
  ) %>% 
  mutate(usage = case_when(rating == 5 ~ 1,
                           rating == 0 ~ 0,
                           rating == 1 ~ 2,
                           rating == 2 ~ 3,
                           rating == 3 ~ 4,
                           rating == 4 ~ 5)) %>% 
    group_by(media_type, state) %>% 
  summarise(avg_use = round(mean(usage, na.rm = T), digits = 3),
            media_type = as.factor(media_type)) %>% 
  add_column(Country = "Nigeria") %>% 
  select(4, everything())



## Wrangling some more data, essentially, converting columsn into rows, recoding values, adding the country as a column to allow for plotting on Tableau
mediatype_state <- full_set %>% 
 select(1, 6:10) %>% 
  pivot_longer(
    cols = c(2:6),
    names_to = "media_type",
    values_to = "rating"
  ) %>% 
  mutate(usage = case_when(rating == 5 ~ 1,
                           rating == 0 ~ 0,
                           rating == 1 ~ 2,
                           rating == 2 ~ 3,
                           rating == 3 ~ 4,
                           rating == 4 ~ 5)) %>% 
  mutate(media_type = as.factor(media_type)) %>% 
  add_column(Country = "Nigeria") %>% 
  select(-3)

 

## A plot to discover which media is most used 
media_by_state <- full_set2 %>% 
  ggplot(aes(fct_rev(fct_relevel(media_type, "Radio", "Television",
                         "Newspaper",  "Internet", "Social Media")), avg_use)) +
  geom_col(aes(fill = media_type)) +
    ylim(0.0, 5.0) +
 # facet_wrap(~ state) +
  scale_fill_OkabeIto(name = "media_type") +
    coord_flip() +
    theme_classic() +
     theme(axis.line = element_blank(),
           panel.background = element_blank(),
           axis.ticks = element_blank(),
           axis.text.y = element_text(size = 10, family="Times", 
                                      face="bold", hjust = 1, 
                                      color = "grey10"),
           legend.position = "none",
           panel.grid.major.x = element_line(color = "grey90",
                                          size = 0.5,
                                          linetype = 1)) +
  labs(title = "",
       x = "", 
          y = "Average Ratings (1 = Never, 5 = Every day)",
       caption = "How often do you get news from the following sources") +
   theme(legend.position="none",
        plot.title=element_text(family="Times", face="bold", size=10),
        axis.title.x  = element_text(family = "Comic Sans MS", face="bold", size=10),
        axis.title.y  = element_text(family = "Times New Roman", face="bold"))


```

## Row {data-height="300"}

### Radio Remains the Main Source of News in Nigeria

```{r warning=FALSE}
media_by_state

```

```{r, warning=FALSE, echo=TRUE, eval=FALSE, include=FALSE}
## Just for Tableau: Attaching geographic data to media usage in order to create graphs on Tableau



tablaeu <- full_set %>% 
   add_column(Country = "Nigeria") %>% 
 rename(Social_Media = "Social Media") %>% 
 select(1, 6:9, 11) %>%
   pivot_longer(
    cols = c(2:5),
    names_to = "media_type",
    values_to = "ratings") %>% 
  mutate(ratings_c = as.character(ratings))


tablaeu2 <- tablaeu %>%
  mutate(NAME_1 = as.character(state))

Media_Use_State <- left_join(NGA1,tablaeu2)
class(tablaeu2$NAME_1)

### Tree map
  treemap_media <- full_set %>% 
  mutate(NAME_1 = as.character(state)) %>% 
      select(11, 6:10)
  
  # make it interactive ("rootname" becomes the title of the plot):
  p <- treemap( treemap_media,
            index="NAME_1",
            vSize="Radio",
            type="index",
           border.col="white",  
           border.lwds=c(1,1)
            )

```

## Column {data-width="400"}

### Ogun State has the highest radio use, followed by Kaduna and Gombe State

```{r warning=FALSE, eval=TRUE}

knitr::include_graphics(here( "final draft graphics", "Radio By State.png"))

```

### Internet use is highest in federal Captial Territory, the capital of Nigera, followed by Borno State 

```{r warning=FALSE, eval=TRUE}

knitr::include_graphics(here( "final draft graphics", "internet use treemap.png"))

```